<?php
/** 
 * Created by RisingSun. 
 * User: MarkSpace 
 * Date: 20210822
 * Time: 11:05 
 * 盈利率管理
 */
namespace app\api\controller;

use  Mscore\Core\Controller;
use  app\api\model\Trade as TradeModel;
use  app\api\model\Common as CommonModel;
use  app\api\model\Login as LoginModel;
use  Mscore\Core\Util\Util;
use  Mscore\Core\Lang;

class TradeController extends Controller{

    private $model;
    private $login;
    private $error;
    private $success;

    /**
     * 初始化自动连接方法
     * @param array $__construct 
     * @param array $where 
    */
    public function __construct()  
    {    
        $this->model = new TradeModel;
        $this->login = (new LoginModel)->isAuth();
        $this->header =get_all_headers();
        $this->header['language']=isset($this->header['language'])&&!empty($this->header['language'])?$this->header['language']:config('langs.default');
        Lang::init($this->header['language']);
        $this->success=Lang::get('Success');
        $this->error=Lang::get('Error');
    }

    /**
     * 产品类别列表
     * @param array $catelist 
     * @param array $where 
     */ 
    public function catelist(){
        $cate=[];
        switch (true) {
            case !empty(post('id')):
                $where = 'a.id='.post('id');
                $cate = $this->model->catelist($where);
                $this->success['data']=$cate['data'];
                $this->success['count']=$cate['total'];
                return $this->echojson($this->success);
                break;
            default:
                $page = post('page',1);
                $limit = post('limit',10);
                $where = 'a.dels<1 and a.status<2';
                $cate = $this->model->catelist($where,$page,$limit);
                if(!empty($cate['data'])){
                    foreach ($cate['data'] as $key => $value) {
                        if(!empty($cate['titles'])){
                            $cate['data'][$key]['title']=isset(json_decode($value['titles'],true)[$this->header['language']])?json_decode($value['titles'],true)[$this->header['language']]:$value['title'];  
                        }
                        unset($cate['data'][$key]['titles']);
                    }
                }
                $this->success['data']=$cate['data'];
                $this->success['count']=$cate['total'];
                return $this->echojson($this->success);
                break;
        } 
    }

    /**
     * 产品列表
     * @param array $trade 
     * @param array $where 
     */ 
    public function trade(){
        $pro=[];
        switch (true) {
            case !empty(post('id')):
                $where = 'a.id='.post('id');
                $pro = $this->model->trade($where);
                if(!empty($pro['data'][0]['titles'])){
                    $pro['data'][0]['title']=isset(json_decode($pro['data'][0]['titles'],true)[$this->header['language']])?json_decode($pro['data'][0]['titles'],true)[$this->header['language']]:$pro['data'][0]['title'];
                    $pro['data'][0]['price']=0;
                    unset($pro['data'][0]['titles']);
                }
                $this->success['data']=$pro['data'];
                $this->success['count']=$pro['total'];
                return $this->echojson($this->success);
                break;
            default:
                $page = post('page',1);
                $limit = post('limit',10);
                $where = 'a.dels<1 and a.status<3';
                if(!empty(post('cid'))){
                    $where .= ' and a.cid='.post('cid');
                }
                if(!empty(post('keyworld'))){
                	$where .= ' and ( a.title like "%'.post('keyworld').'%" or a.procode like "%'.post('keyworld').'%" ) ';
                }
                $pro = $this->model->trade($where,$page,$limit);
                $procode = '';
                foreach ($pro['data'] as $key => $value) {
                    if(!empty($value['titles'])){
                        $pro['data'][$key]['title']=isset(json_decode($value['titles'],true)[$this->header['language']])?json_decode($value['titles'],true)[$this->header['language']]:$value['title'];  
                    }
                    $pro['data'][$key]['price']=0;
                    $procode .= $value['procode'].',';
                    unset($pro['data'][$key]['titles']);
                }
                $this->success['data']=$pro['data'];
                $this->success['procode']=$procode;
                $this->success['count']=$pro['total'];
                return $this->echojson($this->success);
                break;
        } 
    }

    /**
     * 产品详情
     * @param array $tradeinfo 
     * @param array $where 
     */ 
    public function tradeinfo(){
        $id=post('id');
        switch (true) {
            case $id>0:
                $where = ' id='.$id;
                $pro = $this->model->tradeinfo($where);
                if(!empty($pro['titles'])){
                    $pro['title']=isset(json_decode($pro['titles'],true)[$this->header['language']])?json_decode($pro['titles'],true)[$this->header['language']]:$pro['title'];
                    unset( $pro['titles']);
                }
                if(!empty($pro['beatpoint'])){ 
                    $pro['beatpoint']=json_decode($pro['beatpoint'],true);
                }else{
                    $pro['beatpoint']=[];
                }
                if(!empty($pro['opentime'])){
                    $pro['opentime']=json_decode($pro['opentime'],true);
                }else{
                    $pro['opentime']=[];
                }
                if(!empty($pro['retfee'])){
                    $pro['retfee']=json_decode($pro['retfee'],true);
                }else{
                    $pro['retfee']=[];
                }
                if(!empty($pro['exchange'])){
                    $pro['exchange']=json_decode($pro['exchange'],true);
                }else{
                    $pro['exchange']=[];
                }
                if(!empty($pro['fusing'])){
                    $pro['fusing']=json_decode($pro['fusing'],true);
                }else{
                    $pro['fusing']=[];
                }
                if(isset($pro)&&!empty($pro)){
                    $fk=$this->model->getorderinfo(' aid='.$this->login['aid'].' and proid='.$id.' and status<2','id');     
                }
                $pro['orderid']=isset($fk['id'])&&!empty($fk['id'])?$fk['id']:1; //2有订单，1无订单
                $this->success['data']=$pro;
                $this->success['count']=1;
                return $this->echojson($this->success);
                break;
            default:
                return $this->echojson($this->error);
                break;
        }
    }
    
    /**
     * 获取k线图
     */
    public function getKdata(){
        $procode = post('procode',false);
        $page = post('page',1);
        $size = post('page_size',100);
        $time = post('time','1H'); //1M,5M,10M,15M,30M,1H,2H,4H,D,W,M
        if(!$procode){
            return $this->echojson($this->error);
        }
        $data = $this->model->getKdata($procode.'-'.$time.'-'.$page.'-'.$size);
        if(empty($data)){
            $data = $this->model->getApi("procode={$procode}&time={$time}&page={$page}&size={$size}&withlast=0");
            $data = json_decode($data,true);
            if(!isset($data['code']) || $data['code']!=200){
            	$code = isset($data['code'])?$data['code']:103;
                $msg = isset($data['code'])?$data['msg']:'数据请求，接口无反应，请检查网络或其它错误';
                return $this->echojson(['code'=>$code,'msg'=>$msg]);
            }
            if(isset($data['data'])&&!empty($data['data'])){
                $settime=60*60;
                switch ($time) {
                    case '1M':
                        $settime=60;
                        break;
                    case '5M':
                        $settime=60*5;
                        break;
                    case '30M':
                        $settime=60*30;
                        break;
                    case '1H':
                        $settime=60*60;
                        break;
                    case 'D':
                        $settime=60*60*24;
                        break;
                    default:
                        $settime=60*60;
                        break;
                }
                $this->model->setKdata($procode.'-'.$time.'-'.$page.'-'.$size,$data['data'],$settime);
            }
            $data = $data['data'];
        }
        $this->success['data']=$data;
        return $this->echojson($this->success);
    }
    /**
     * 订单list
     * @param array $orderlist 
     * @param array $where 
     */ 
    public function orderlist(){
        switch (true) {
            case !empty(post('id')):
                $where = 'id='.post('id');
                $datalist = $this->model->list($where);
                if(!empty($datalist['data'][0]['titles'])){
                    $datalist['data'][0]['proname']=isset(json_decode($datalist['data'][0]['titles'],true)[$this->header['language']])?json_decode($datalist['data'][0]['titles'],true)[$this->header['language']]:$datalist['data'][0]['proname'];
                    unset($datalist['data'][0]['titles']); 
                }
                $this->success['data']=$datalist['data'];
                $this->success['count']=$datalist['total'];
                return $this->echojson($this->success);
                break;
            default:
                $page = post('page',1);
                $limit = post('limit',10);
                $where = ' dels<1 and aid = '.$this->login['aid'];
                if(post('time')){
                    $time=post('time');
                    switch ($time){
                        case 1:
                            $where .= '';
                            break;
                        case 2:
                            $where .= " and (createtime BETWEEN CONCAT(CURDATE(),' 00:00:00') AND CONCAT(CURDATE(),' 23:59:59')) ";
                            break;
                        case 3:
                            $where .= ' and (TO_DAYS(NOW()) - TO_DAYS(createtime) = 1)';
                            break;
                        case 4:
                            $where .= ' and (WEEK(createtime) = WEEK(CURDATE()))';
                            break;
                        case 5:
                            $where .= " and DATE_FORMAT(createtime,'%Y-%m')= DATE_FORMAT(CURDATE(),'%Y-%m')";
                            break;
                        case 6:
                            $where .= " and (PERIOD_DIFF(DATE_FORMAT(NOW(),'%Y%m'),DATE_FORMAT(createtime,'%Y%m')) = 1)";
                            break;
                        default:
                            return $this->echojson($this->error);
                            break;
                    }
                    
                }
                $datalist = $this->model->list($where,$page,$limit);
                foreach ($datalist['data'] as $key => $value) {
                    if(!empty($value['titles'])){
                        $datalist['data'][$key]['proname']=isset(json_decode($value['titles'],true)[$this->header['language']])?json_decode($value['titles'],true)[$this->header['language']]:$value['proname']; 
                        unset($datalist['data'][$key]['titles']);
                    }
                }
                $this->success['data']=!empty($datalist['data'])?$datalist['data']:[];
                $this->success['count']=$datalist['total'];
                return $this->echojson($this->success);
                break;
        } 
    }

    /**
     * orderlistrun
     * @param array $orderlistrun 
     * @param array $where 
     */ 
    public function orderlistrun(){
        switch (true) {
            case !empty(post('id')):
                $where = 'id='.post('id');
                $datalist = $this->model->list($where);
                if(!empty($datalist['data'][0]['titles'])){
                    $datalist['data'][0]['proname']=isset(json_decode($datalist['data'][0]['titles'],true)[$this->header['language']])?json_decode($datalist['data'][0]['titles'],true)[$this->header['language']]:$datalist['data'][0]['proname']; 
                    unset($datalist['data'][0]['titles']); 
                }
                if(!empty($datainfo)){
                    $$datalist['data'][0]['record'] = $this->model->getorderloglist('status<2 and orderid = ' . $datainfo['id'],'id');
                }else{
                    $$datalist['data'][0]['record'] = [];
                }
                $this->success['data']=$datalist['data'];
                $this->success['count']=$datalist['total'];
                return $this->echojson($this->success);
                break;
            default:
                $page = post('page',1);
                $limit = post('limit',10);
                $where = ' dels<1 and aid = '.$this->login['aid'].' and status<2 ';
                // if(post('proname')){
                //     $where .= ' and proname like "%'.post('proname').'%"';
                // }
                $datalist = $this->model->list($where,$page,$limit);
                foreach ($datalist['data'] as $key => $value) {
                    if(!empty($value['titles'])){
                        $datalist['data'][$key]['proname']=isset(json_decode($value['titles'],true)[$this->header['language']])?json_decode($value['titles'],true)[$this->header['language']]:$value['proname']; 
                        unset($datalist['data'][$key]['titles']);
                    }
                    if(!empty($datalist['data'])){
                        $datalist['data'][$key]['record'] = $this->model->getorderloglist(' orderid = ' . $value['id'],'id');
                        $closestatus = $this->model->getorderloginfo(' status<2 and orderid = ' . $value['id'],'id');
                        $datalist['closestatus']=isset($closestatus['id'])||!empty($closestatus['id'])?1:2;
                    }else{
                        $datalist['data'][$key]['record'] = [];
                        $datalist['closestatus'] =2 ;
                    }
                }
                $this->success['data']=!empty($datalist['data'])?$datalist['data']:[];
                $this->success['count']=$datalist['total'];
                $this->success['closestatus']=!empty($datalist['closestatus'])?$datalist['closestatus']:2;
                return $this->echojson($this->success);
                break;
        } 
    }
    /**
     * 订单信息
     * @param array $orderinfo 
     * @param array $where 
     */ 
    public function orderinfo(){
        switch (true) {
            case !empty(post('id')):
                $id=post('id');
                $where = 'id='.$id;
                $datainfo = $this->model->getorderinfo($where);
                if(!empty($datainfo['titles'])){
                    $datainfo['proname']=isset(json_decode($datainfo['titles'],true)[$this->header['language']])?json_decode($datainfo['titles'],true)[$this->header['language']]:$datainfo['proname']; 
                    unset($datainfo['titles']); 
                }
                if(!empty($datainfo['point'])){
                    $datainfo['point']=json_decode($datainfo['point'],true); 
                }else{
                    $datainfo['point']=['winpoint'=>0,'losspoint'=>0];
                }
                if(!empty($datainfo)){
                    $datainfo['record'] = $this->model->getorderloglist('type<7 and orderid = ' . $datainfo['id']);
                }else{
                    $datainfo['record'] = [];
                }
                
                $this->success['data']=$datainfo;
                return $this->echojson($this->success);
                break;
            default:
                return $this->echojson($this->error);
                break;
        } 
    }

    /**
     * 订单list
     * @param array $orderloglistrun 
     * @param array $where 
     */ 
    public function orderloglistrun(){
        switch (true) {
            case !empty(post('id')):
                $where = 'a.id='.post('id');
                $datalist = $this->model->orderloglist($where);
                if(!empty($datalist['data'][0]['titles'])){
                    $datalist['data'][0]['proname']=isset(json_decode($datalist['data'][0]['titles'],true)[$this->header['language']])?json_decode($datalist['data'][0]['titles'],true)[$this->header['language']]:$datalist['data'][0]['proname']; 
                    unset($datalist['data'][0]['titles']); 
                }
                $this->success['data']=$datalist['data'];
                $this->success['count']=$datalist['total'];
                return $this->echojson($this->success);
                break;
            default:
                $page = post('page',1);
                $limit = post('limit',10);
                $where = ' a.aid = '.$this->login['aid'].' and a.status<2 ';
                $datalist = $this->model->orderloglist($where,$page,$limit);
                foreach ($datalist['data'] as $key => $value) {
                    if(!empty($value['titles'])){
                        $datalist['data'][$key]['proname']=isset(json_decode($value['titles'],true)[$this->header['language']])?json_decode($value['titles'],true)[$this->header['language']]:$value['proname']; 
                        unset($datalist['data'][$key]['titles']);
                    }
                }
                $this->success['data']=!empty($datalist['data'])?$datalist['data']:[];
                $this->success['count']=$datalist['total'];
                return $this->echojson($this->success);
                break;
        } 
    }

    /**
     * orderloglist
     * @param array $orderloglist 
     * @param array $where 
     */ 
    public function orderloglist(){
    	$where = ' aid = '.$this->login['aid'].' and orderid= '.post('orderid');
        $datalist = $this->model->getorderloglist($where);
        foreach ($datalist as $key => $value) {
            if(!empty($value['titles'])){
                $datalist[$key]['proname']=isset(json_decode($value['titles'],true)[$this->header['language']])?json_decode($value['titles'],true)[$this->header['language']]:$value['proname']; 
                unset($datalist[$key]['titles']);
            }
        }
        $this->success['data']=!empty($datalist)?$datalist:[];
        return $this->echojson($this->success);
    }

    /**
     * 获取参数
     * @param array $getconfshow 
     * @param array $where 
     */ 
    public function getconfshow(){
        $control=(new CommonModel())->getBaseinfo('keyname="tradecontrol"','content');
        $control=!empty($control)?$control['content']:config('tradecontrol');
        $this->success['data']=$control;
        return $this->echojson($this->success); 
    }

    /**
     * 订单orderadd
     * @param array $orderadd 
     * @param array $where 
     */ 
    public function orderadd(){
        $params = post();
        //判斷參數是否存在
        if(empty($params['proid'])) return $this->echoJson(Lang::get('Proempty'));
        if(empty($params['order_type'])) return $this->echoJson(Lang::get('Updown'));

        if(empty($this->login['aid'])) return $this->echoJson(Lang::get('Getusererror'));
        $user=(new CommonModel())->getAccount('aid='.$this->login['aid'],['aid','amount','giftamount','pid','paypwd']);

        $control=(new CommonModel())->getBaseinfo('keyname="tradecontrol"','content');
        $control=!empty($control)?$control['content']:config('tradecontrol');
        //判斷支付密碼及驗證
        if($control['addorder']==1){
            if(empty($params['pay_password'])) return $this->echoJson(Lang::get('Paypwdempty'));
            if(empty($user['paypwd'])) return $this->echoJson(Lang::get('Paypwdset'));
            if (!Util::passwordVerify($params['pay_password'], $user['paypwd'])) return $this->echojson(Lang::get('Paypwderror'));
        }
        //獲取運營參數
        $pro = $this->model->tradeinfo('id='.$params['proid'],['id','title','titles','procode','price','bond','orders','fee','minnum','maxnum','selltime','ratio','beatpoint','retention','fusing']);
        if(empty($pro)) return $this->echoJson(Lang::get('Nodata'));
        //獲取訂單數
        if($pro['orders']==1){
            $count=$this->model->getorderinfo('proid='.$params['proid'].' and status<2 and aid='.$this->login['aid'],'count(id) as id');
            if(isset($count['id'])&&!empty($count['id'])){
                return $this->echoJson(Lang::get('Ordercz'));
            }
        }
        //获取跳动参数
        if(!empty($pro['beatpoint'])){
            $pro['beatpoint'] = json_decode($pro['beatpoint'],true);
        }else{
            $pro['beatpoint'] = ["top"=>"0","low"=>"0","rands"=>"1","length"=>"2"];
        }
        //平仓线及预警线
        $pro['ratio'] = json_decode($pro['ratio'],true);
        $pro['ratio'] = !empty($pro['ratio']['ratio'])?$pro['ratio']['ratio']:$control['ratio'];
        $pro['warn'] = !empty($pro['ratio']['warn'])?$pro['ratio']['warn']:$control['warn'];
        //獲取產品口數
        $puffs=$this->model->getorderloginfo('proid='.$params['proid'].' and status<2 and aid='.$this->login['aid'],'sum(puffs) as puffs');
        if(!empty($pro['minnum'])&&$pro['minnum']>intval($params['puffs']+$puffs['puffs'])) return $this->echoJson(Lang::get('Ordermin'));
        if(!empty($pro['maxnum'])&&$pro['maxnum']<intval($params['puffs']+$puffs['puffs'])) return $this->echoJson(Lang::get('Ordermax'));
        //判断其他参数
        if($params['money_type']==1){
           if($user['amount']<floatval($params['puffs']*$pro['bond'])) return $this->echoJson(Lang::get('Amountfew'));  //用戶金額
        }elseif($params['money_type']==2){
           if($user['giftamount']<floatval($params['puffs']*$pro['bond'])) return $this->echoJson(Lang::get('Amountfew')); //虛擬金額
        }
        //获取产品现价
        $price = $this->model->getprice($pro['procode']);
        if(empty($price['price'])){
            return $this->echojson(Lang::get('Ordererror'));
        }
        //获取手续费
        if(isset($pro['fee'])&&!empty($pro['fee'])){
            $sx_fee = $pro['fee']*$params['puffs'];
        }else{
            $sx_fee = (new CommonModel())->getBaseinfo('keyname="payment"','content')['content']['fixorder'];
            $sx_fee = round(floatval($params['puffs'])*floatval($sx_fee));
        }
        // 获取是否小盘
        $params['endtime']=0;
        $params['lc_fee'] = 0;
        switch ($control['mode']) {
            case 2:
                $pro['selltime']=json_decode($pro['selltime'],true);
                if(empty($pro['selltime'][date("W")])){
                    if(!empty($price['endtime'])){
                        $params['endtime'] = data('Y-m-d').' '.$price['endtime']; 
                        $params['endtime']=strtotime($params['endtime']);//转时间戳
                    }
                }else{
                    $params['endtime'] = data('Y-m-d').' '.$pro['selltime'][date("W")]; 
                    $params['endtime']=strtotime($params['endtime']);//转时间戳
                }
                break;
            default:
                if(!empty($control['modedata'])){
                    $modedata=explode(",", $control['modedata']);
                    if(isset($modedata[0])&&!empty($modedata[0])){
                        $params['endtime']=time()+$modedata[0]*24*60*60;
                    }
                    if(isset($modedata[1])&&!empty($modedata[1])){
                        $params['lc_fee']=$modedata[1]*$sx_fee/100;
                    }
                }
                break;
        }
        //停損停利
        $pro['point']=['winpoint'=>$params['winpoint'],'losspoint'=>$params['losspoint']];
        //获取保证金
        $pro['moneysum']=$pro['bond']*$params['puffs'];
        //判断是否预挂还是直接买入
        switch ($params['waitbuy']) {
            case 1:
                $wpoint=0;
                $status=1; //直接买入
                break;
            case 2:
                $wpoint=$params['waitpoint'];
                $status=0; //预挂
                break;
            default:
                return $this->echojson(Lang::get('Parerror'));
                break;
        }
        //下单口数参数
        $puffs=$params['puffs'];
        $protype=$params['protype'];
        //订单参数
        $params=[
            'order_no'=>getNumID(6,'order',1),//年月日加8位计数,order文件计数名称，1代表类别，1订单
            'type'=>$params['money_type'],
            'aid'=>$user['aid'],
            'pid'=>$user['pid'],
            'waitbuy'=>$params['waitbuy'],
            'price'=>$pro['price'],
            'bond'=>$pro['bond'],
            'lc_fee'=>$params['lc_fee'],
            'wpoint'=>$wpoint,
            'proid'=>$pro['id'],
            'rands'=>$pro['beatpoint']['rands'],
            'proname'=>$pro['title'],
            'titles'=>$pro['titles'],
            'procode'=>$pro['procode'],
            'updown'=>$params['order_type'],
            'money'=>0,
            'retention'=>$pro['retention'],
            'endtime'=>$params['endtime'],
            'status'=>$status,
            'createtime'=>date('Y-m-d H:i:s',time())
        ];
        (new CommonModel())->startTrans();
        try {
            //获取下单余额控制参数
            switch ($params['type']) {
                case 1:
                    $amount = $user['amount'];
                    $money = ($user['amount']-$pro['moneysum']-$sx_fee);
                    if($money<=0){ return $this->echoJson(Lang::get('Amountfew')); }
                    $info = (new CommonModel())->updateAccount('aid='.$user['aid'],['amount'=>$money]);
                    break;
                case 2:
                    $amount = $user['giftamount'];
                    $money = ($user['giftamount']-$pro['moneysum']-$sx_fee);
                    if($money<=0){ return $this->echoJson(Lang::get('Amountfew')); }
                    $info = (new CommonModel())->updateAccount('aid='.$user['aid'],['giftamount'=>$money]);
                    break;
                default:
                    return $this->echoJson($this->error);
                    break;
            }
            $id=$this->model->addorder($params);
            if($id){
                //设定预挂价格
                if($params['waitbuy']==2){
                    $price['price']=$params['updown']==1?($price['price']*10000+$wpoint*$pro['beatpoint']['rands']*10000)/10000:($price['price']*10000-$wpoint*$pro['beatpoint']['rands']*10000)/10000;
                }
                $data=[
                    'order_no'=>$params['order_no'],
                    'orderid'=>$id,
                    'aid'=>$user['aid'],
                    'pid'=>$user['pid'],
                    'type'=>1,
                    'proid'=>$pro['id'],
                    'protype'=>$protype,
                    'buyprice'=>$price['price'],
                    'point'=>json_encode($pro['point'],JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE),
                    'bondsum'=>round($pro['moneysum'],2),
                    'closesum'=>round(($pro['ratio']*$pro['moneysum']/100),2),
                    'warnsum'=>round(($pro['warn']*$pro['moneysum']/100),2),
                    'puffs'=>$puffs,
                    'sx_fee'=>$sx_fee,
                    'amount'=>$amount,
                    'backamount'=>$money,
                    'createtime'=>date('Y-m-d H:i:s',time())
                ];
                $rid=$this->model->addorderlog($data);
            }
            $this->model->updateorder('id='.$id,['subid'=>$rid]);
            (new CommonModel())->commit();
            //导入redis
            unset($params['titles'],$data);
            $data=[
                'id'=>$id,//订单id
                'rid'=>$rid, //记录id
                'type'=>$params['type'],
                'aid'=>$user['aid'],
                'pid'=>$user['pid'],
                'proid'=>$pro['id'],
                'protype'=>$protype,
                'rands'=>$pro['beatpoint']['rands'],
                'procode'=>$pro['procode'],
                'updown'=>$params['updown'],
                'endtime'=>$params['endtime'],
                'status'=>$status,
                'waitbuy'=>$params['waitbuy'],
                'buyprice'=>$price['price'],
                'bond'=>$pro['bond'],
                'point'=>$pro['point'],
                'bondsum'=>round($pro['moneysum'],2),
                'closesum'=>round(($pro['ratio']*$pro['moneysum']/100),2),
                'warnsum'=>round(($pro['warn']*$pro['moneysum']/100),2),
                'warn'=>0,
                'price'=>$pro['price'],
                'puffs'=>$puffs,
                'money'=>0,
            ];
            $pro['fusing'] = json_decode($pro['fusing'],true);
            if($pro['fusing']['up']>0&&$pro['fusing']['down']>0){
                $data['fusing']=$pro['fusing'];
            }
            switch ($params['waitbuy']) {
                case 1:
                    $this->model->execRedis('hset',[config('tradecontrol.order'), $rid,json_encode($data)]);
                    break;
                case 2:
                    $this->model->execRedis('hset',[config('tradecontrol.ygorder'), $rid,json_encode($data)]);
                    break;
                default:
                    return $this->echojson(Lang::get('Parerror'));
                    break;
            }
            unset($params);
            //成功
            return $this->echojson($this->success);
        } catch (Exception $e) {
            (new CommonModel())->rollback();
            return $this->echojson(Lang::get('Parerror'));
        }
    }

    /**
     * 订单平仓
     * @param array $orderbuynow 
     * @param array $where 
     */ 
    public function orderbuynow(){
        $params = post();
        //判斷參數是否存在
        if(empty($params['id'])) return $this->echoJson(Lang::get('Ordererror'));
        //判斷用户
        if(empty($this->login['aid'])) return $this->echoJson(Lang::get('Getusererror'));
        //获取订单
        $orders = $this->model->getorderloginfo('id='.$params['id'],'id,orderid');
        //获取订单
        $order = $this->model->getorderinfo('id='.$orders['orderid'],'id,order_no,aid,pid');
        //獲取订单參數名称
        $key = config('tradecontrol.ygorder');
        $redata = $this->model->execRedis('hget',[$key,$orders['id']]);
        $redata = json_decode($redata,true);
        $price = $this->model->getprice($redata['procode']);
        (new CommonModel())->startTrans();
        try {
            $data=[
                'waitbuy'=>1,
                'status'=>1
            ];
            $status = $this->model->updateorder('id='.$order['id'],$data);
            $data=[
                'buyprice'=>round($price['price'],$price['length']),
                'status'=>1
            ];
            $status = $this->model->updateorderlog('id='.$orders['id'],$data); 
            (new CommonModel())->commit();
            $okey = config('tradecontrol.order');
            $redata['buyprice']=$price['price'];
            $redata['status']=1;
            $redata['waitbuy']=1;
            $this->model->execRedis('hset',[$okey,$order['id'],json_encode($redata,JSON_UNESCAPED_UNICODE|JSON_UNESCAPED_SLASHES)]);
            $this->model->execRedis('hdel',[$key,$order['id']]);
            return $this->echojson($this->success);
        } catch (Exception $e) {
            (new CommonModel())->rollback();
            return $this->echojson(Lang::get('Parerror'));   
        }
    }

    /**
     * 取消预挂
     * @param array $ordercancel 
     * @param array $where 
     */ 
    public function ordercancel(){
        $params = post();
        //判斷參數是否存在
        if(empty($params['id'])) return $this->echoJson(Lang::get('Ordererror'));
        //判斷用户
        if(empty($this->login['aid'])) return $this->echoJson(Lang::get('Getusererror'));
        $user=(new CommonModel())->getAccount('aid='.$this->login['aid'],['aid','amount','giftamount','pid','paypwd']);
        //获取订单
        $orders = $this->model->getorderloginfo('id='.$params['id'],'id,orderid,sx_fee,bondsum');
        //获取订单
        $order = $this->model->getorderinfo('id='.$orders['orderid'],'id,order_no,aid,pid,type');
        //獲取订单參數名称
        $key = config('tradecontrol.ygorder');
        // $redata = $this->model->execRedis('hget',[$key,$orders['id']]);
        // $redata = json_decode($redata,true);
        (new CommonModel())->startTrans();
        try {
            //获取下单余额控制参数
            switch ($order['type']) {
                case 1:
                    $amount = $user['amount'];
                    $money = ($user['amount']+$orders['bondsum']+$orders['sx_fee']);
                    $info = (new CommonModel())->updateAccount('aid='.$user['aid'],['amount'=>$money]);
                    break;
                case 2:
                    $amount = $user['giftamount'];
                    $money = ($user['giftamount']+$orders['bondsum']+$orders['sx_fee']);
                    $info = (new CommonModel())->updateAccount('aid='.$user['aid'],['giftamount'=>$money]);
                    break;
                default:
                    return $this->echoJson($this->error);
                    break;
            }
            $data=[
                'status'=>5
            ];
            $status = $this->model->updateorder('id='.$order['id'],$data);
            $data=[
                'status'=>5
            ];
            $status = $this->model->updateorderlog('id='.$orders['id'],$data); 
            (new CommonModel())->commit();
            $this->model->execRedis('hdel',[$key,$orders['id']]);
            $this->model->execRedis('hdel',[$key.$this->login['aid'],$orders['id']]);
            return $this->echojson($this->success);
        } catch (Exception $e) {
            (new CommonModel())->rollback();
            return $this->echojson(Lang::get('Parerror'));   
        }
    }

    /**
     * 订单平仓
     * @param array $ordersettle 
     * @param array $where 
     */ 
    public function ordersettle(){
        $params = post();
        //判斷參數是否存在
        if(empty($params['orderid'])) return $this->echoJson(Lang::get('Ordererror'));
        //判斷用户
        if(empty($this->login['aid'])) return $this->echoJson(Lang::get('Getusererror'));
        $user=(new CommonModel())->getAccount('aid='.$this->login['aid'],['aid','amount','giftamount']);
        //获取订单
        $order = $this->model->getorderinfo('id='.$params['orderid'],'id,order_no,aid,pid,subid,type,money');
        //獲取订单參數名称
        $key = config('tradecontrol.order');
        //获取订单计算
        $subid = explode(",", $order['subid']);
        //获取账户余额
        switch ($order['type']) {
            case 1:
                $amount=$user['amount'];
                break;
            case 2:
                $amount=$user['giftamount'];
                break;
            default:
                return $this->echojson(Lang::get('Parerror'));
                break;
        }
        //初始化金额
        $money=0;$bondsum=0;
        //开启事务
        (new CommonModel())->startTrans();
        try {
            foreach ($subid as $k => $value) {
                $orders = $this->model->execRedis('hget',[$key,$value]);
                if(!empty($orders)){
                    $orders = json_decode($orders,true);
                }else{
                    continue;
                }
                // 确定输赢
                switch (true) {
                    case $orders['money']>0:
                        $orders['win']=1;
                        break;
                    case $orders['money']<0:
                        $orders['win']=2;
                        break;
                    default:
                        $orders['win']=0;
                        break;
                }
                // 浮动金额
                $change=0;
                if(isset($orders['drift'])&&!empty($orders['drift'])&&$orders['protype']==1){
                    $orders['money'] = $orders['money'] + $orders['drift']*$orders['money']/100;
                    $change=$orders['drift']*$orders['money']/100;
                    $orders['difference'] = $orders['difference'] + $orders['drift']*$orders['difference']/100;
                    $orders['sellprice'] = $orders['buyprice'] + $orders['difference']*$orders['rands'];
                }
                $data = [
                    'money'=>$orders['money'],
                    'change'=>$change,
                    'win'=>$orders['win'],
                    'status'=>2,
                    'wlpoint'=>$orders['difference'],
                    'sellprice'=>$orders['sellprice'],
                    'updatetime'=>date('Y-m-d H:i:s',time())
                ];
                $this->model->updateorderlog('id='.$orders['rid'],$data);
                $data=[
                    'order_no'=>$order['order_no'],
                    'orderid'=>$order['id'],
                    'type'=>7,
                    'aid'=>$order['aid'],
                    'pid'=>$order['pid'],
                    'proid'=>$orders['proid'],
                    'buyprice'=>$orders['buyprice'],
                    'sellprice'=>$orders['sellprice'],
                    'wlpoint'=>$orders['difference'],
                    'amount'=>$amount,
                    'backamount'=>$amount+$orders['money']+$orders['bondsum'],
                    'puffs'=>$orders['puffs'],
                    'win'=>$orders['win'],
                    'status'=>2,
                    'createtime'=>date('Y-m-d H:i:s',time())
                ];
                $info = $this->model->addorderlog($data);
                $money += $orders['money'];
                $bondsum += $orders['bondsum'];
                $this->model->execRedis('hdel',[$key,$value]);
                $this->model->execRedis('hdel',[$key.$this->login['aid'],$value]);
            }
            // 初始化金额
            // $money=0;$bondsum=0;
            // $moneysum=$this->model->getorderloginfo(' orderid = '.$order['id'],' sum(money) as money, sum(bondsum) as bondsum ');
            // $money = $moneysum['money'];
            // $bondsum = $moneysum['bondsum'];
            //获取资金数
            $moneysum = $bondsum + $money;
            //更新账户余额
            $control=config('tradecontrol');
            // $accmoney = $this->model->execRedis('hget',[$control['amount'], $user['aid']]);
            // if(!empty($accmoney)){ $accmoney = json_decode($accmoney, true); }else{ $accmoney=[]; }
            switch ($order['type']) {
                case 1:
                    (new CommonModel())->updateAccount('aid='.$user['aid'],['amount'=>($amount+$moneysum)]);
                    break;
                case 2:
                    (new CommonModel())->updateAccount('aid='.$user['aid'],['giftamount'=>($amount+$moneysum)]);
                    break;
                default:
                    return $this->echojson(Lang::get('Parerror'));
                    break;
            }
            $data = [
                'money'=>$order['money']+$money,
                'status'=>2,
                'updatetime'=>date('Y-m-d H:i:s',time())
            ];
            $this->model->updateorder('id='.$order['id'],$data);
            $count=$this->model->getorderloginfo('status<2 and aid='.$this->login['aid'],'count(id) as id');
            if($count['id']<1){
                $this->model->execRedis('hdel',[$control['amount'], $user['aid']]);
            }
            (new CommonModel())->commit();
            return $this->echojson($this->success);
        } catch (Exception $e) {
            (new CommonModel())->rollback();
            return $this->echojson(Lang::get('Parerror'));
        }
    }

    /**
     * 订单加仓
     * @param array $orderaddmore 
     * @param array $where 
     */ 
    public function orderaddmore(){
        $params = post();
        //判斷參數是否存在
        if(empty($params['orderid']) || empty($params['puffs'])) return $this->echoJson(Lang::get('Parerror'));
        //判斷用户
        if(empty($this->login['aid'])) return $this->echoJson(Lang::get('Getusererror'));
        $user=(new CommonModel())->getAccount('aid='.$this->login['aid'],['amount','giftamount']);
        //获取订单
        $order = $this->model->getorderinfo('id='.$params['orderid'],'id,order_no,aid,pid,subid,type,proid,updown,endtime,rands');
        $pro = $this->model->tradeinfo('id='.$order['proid'],['id','procode','price','bond','fee','minnum','maxnum','ratio']);
        if(empty($pro)) return $this->echoJson(Lang::get('Nodata'));
        //获取控制参数
        $control=(new CommonModel())->getBaseinfo('keyname="tradecontrol"','content');
        $control=!empty($control)?$control['content']:config('tradecontrol');
        //平仓线及预警线
        $pro['ratio'] = json_decode($pro['ratio'],true);
        $pro['ratio'] = !empty($pro['ratio']['ratio'])?$pro['ratio']['ratio']:$control['ratio'];
        $pro['warn'] = !empty($pro['ratio']['warn'])?$pro['ratio']['warn']:$control['warn'];
        //停損停利
        $pro['point']=['winpoint'=>$params['winpoint'],'losspoint'=>$params['losspoint']];
        //獲取產品口數20241130
        $puffs=$this->model->getorderloginfo('proid='.$pro['id'].' and status<2 and aid='.$this->login['aid'],'sum(puffs) as puffs');
        if(!empty($pro['minnum'])&&$pro['minnum']>intval($params['puffs']+$puffs['puffs'])) return $this->echoJson(Lang::get('Ordermin'));
        if(!empty($pro['maxnum'])&&$pro['maxnum']<intval($params['puffs']+$puffs['puffs'])) return $this->echoJson(Lang::get('Ordermax'));
        //获取产品现价
        $price = $this->model->getprice($pro['procode']);
        if(empty($price['price'])){
            return $this->echojson(Lang::get('Parerror'));
        }
        //获取手续费
        if(isset($pro['fee'])&&!empty($pro['fee'])){
            $sx_fee = $pro['fee']*$params['puffs'];
        }else{
            $sx_fee = (new CommonModel())->getBaseinfo('keyname="payment"','content')['content']['fixorder'];
            $sx_fee = round(floatval($params['puffs'])*floatval($sx_fee));
        }
        //獲取订单參數
        $key = config('tradecontrol.order');
        //获取订单计算
        $subid = explode(",", $order['subid']);
        //获取账户余额
        switch ($order['type']) {
            case 1:
                $amount=$user['amount'];
                break;
            case 2:
                $amount=$user['giftamount'];
                break;
            default:
                return $this->echojson(Lang::get('Parerror'));
                break;
        }
        //开启事务
        (new CommonModel())->startTrans();
        //初始化金额
        $money=0;$bondsum=0;
        try {
            $orders = $this->model->execRedis('hgetall',[$key.$order['aid']]);
            foreach ($orders as $k => $value) {
                if(!empty($value)){
                    $value = json_decode($value,true);
                }else{
                    return $this->echoJson(Lang::get('Nodata'));
                }
                if($value['money']<=0){
                    $money += abs($value['money']); //亏损金额
                }
                // $bondsum += $value['bondsum'];
            }
            $moneysum = $pro['bond']*$params['puffs'];
            if($moneysum>($amount - $money)){
                return $this->echojson(Lang::get('Amountfew'));
            }else{
                $backamount = $amount - $moneysum;
            }
            //写入加仓
            $data=[
                'order_no'=>$order['order_no'],
                'orderid'=>$params['orderid'],
                'aid'=>$order['aid'],
                'pid'=>$order['pid'],
                'type'=>2,
                'proid'=>$order['proid'],
                'protype'=>$params['protype'],
                'buyprice'=>$price['price'],
                'point'=>json_encode($pro['point'],JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE),
                'bondsum'=>round($moneysum,2),
                'closesum'=>round(($pro['ratio']*$moneysum/100),2),
                'warnsum'=>round(($pro['warn']*$moneysum/100),2),
                'puffs'=>$params['puffs'],
                'sx_fee'=>$sx_fee,
                'amount'=>$amount,
                'backamount'=>$backamount,
                'createtime'=>date('Y-m-d H:i:s',time())
            ];
            $rid=$this->model->addorderlog($data);

            //更新账户余额
            switch ($order['type']) {
                case 1:
                    (new CommonModel())->updateAccount('aid='.$order['aid'],['amount'=>$backamount]);
                    break;
                case 2:
                    (new CommonModel())->updateAccount('aid='.$order['aid'],['giftamount'=>$backamount]);
                    break;
                default:
                    return $this->echojson(Lang::get('Parerror'));
                    break;
            }
            $data = [
                'subid'=>$order['subid'].','.$rid,
                'updatetime'=>date('Y-m-d H:i:s',time())
            ];
            $this->model->updateorder('id='.$order['id'],$data);
            (new CommonModel())->commit();
            $data=[
                'id'=>$order['id'],//订单id
                'rid'=>$rid, //记录id
                'type'=>$order['type'],
                'aid'=>$order['aid'],
                'pid'=>$order['pid'],
                'proid'=>$pro['id'],
                'protype'=>$params['protype'],
                'rands'=>$order['rands'],
                'procode'=>$pro['procode'],
                'updown'=>$order['updown'],
                'endtime'=>$order['endtime'],
                'status'=>1,
                // 'rstatus'=>1,
                'buyprice'=>$price['price'],
                'bond'=>$pro['bond'],
                'point'=>$pro['point'],
                'bondsum'=>round($moneysum,2),
                'closesum'=>round(($pro['ratio']*$moneysum/100),2),
                'warnsum'=>round(($pro['warn']*$moneysum/100),2),
                'warn'=>0,
                'price'=>$pro['price'],
                'puffs'=>$params['puffs'],
                'money'=>0,
            ];
            $this->model->execRedis('hset',[config('tradecontrol.order'), $rid, json_encode($data)]);
            return $this->echojson($this->success);
        } catch (Exception $e) {
            (new CommonModel())->rollback();
            return $this->echojson(Lang::get('Parerror'));
        }
    }

    /**
     * 订单減倉
     * @param array $orderreduce 
     * @param array $where 
     */ 
    public function orderreduce(){
        $params = post();
        //判斷參數是否存在
        if(empty($params['id']) || empty($params['puffs'])) return $this->echoJson(Lang::get('Parerror'));
        //判斷用户
        if(empty($this->login['aid'])) return $this->echoJson(Lang::get('Getusererror'));
        $user=(new CommonModel())->getAccount('aid='.$this->login['aid'],['amount','giftamount']);
        //获取订单
        $orders = $this->model->getorderloginfo('id='.$params['id'],'id,orderid,protype,puffs,buyprice,point,bondsum');
        if($params['puffs']>$orders['puffs']){ return $this->echoJson(Lang::get('Parerror')); }
        $order = $this->model->getorderinfo('id='.$orders['orderid'],'id,order_no,aid,pid,type,proid,bond,money,price');
        $pro = $this->model->tradeinfo('id='.$order['proid'],['id','procode','bond','fee','ratio']);
        if(empty($pro)) return $this->echoJson(Lang::get('Nodata'));
        //获取控制参数
        $control=(new CommonModel())->getBaseinfo('keyname="tradecontrol"','content');
        $control=!empty($control)?$control['content']:config('tradecontrol');
        //平仓线及预警线
        $pro['ratio'] = json_decode($pro['ratio'],true);
        $pro['ratio'] = !empty($pro['ratio']['ratio'])?$pro['ratio']['ratio']:$control['ratio'];
        $pro['warn'] = !empty($pro['ratio']['warn'])?$pro['ratio']['warn']:$control['warn'];
        //获取控制参数
        $control=(new CommonModel())->getBaseinfo('keyname="tradecontrol"','content');
        $control=!empty($control)?$control['content']:config('tradecontrol');
        $key = config('tradecontrol.order');
        // 獲取產品
        $redisorder = $this->model->execRedis('hget',[$key, $orders['id']]);
        if(!empty($redisorder)){
            $redisorder = json_decode($redisorder,true);
        }else{
            return $this->echoJson(Lang::get('Nodata'));
        }
        //获取产品现价
        $price = $this->model->getprice($pro['procode']);
        if(empty($price['price'])){
            if(empty($redisorder['sellprice']))  return $this->echojson(Lang::get('Parerror'));
            $price['price']=$redisorder['sellprice'];
        }
        //获取账户余额
        switch ($order['type']) {
            case 1:
                $amount=$user['amount'];
                break;
            case 2:
                $amount=$user['giftamount'];
                break;
            default:
                return $this->echojson(Lang::get('Parerror'));
                break;
        }
        //开启事务
        (new CommonModel())->startTrans();
        //初始化金额
        $money=0;$bondsum=0;$moneysum=0;
        try {
            $money = $redisorder['difference']*$params['puffs']*$order['price'];
            $moneysum = $order['bond']*$params['puffs'];
            $backamount = $amount + $money + $moneysum;
            // 确定输赢
            switch (true) {
                case $money>0:
                    $order['win']=1;
                    break;
                case $money<0:
                    $order['win']=2;
                    break;
                default:
                    $order['win']=0;
                    break;
            }
            // 浮动金额
            $change=0;
            if(isset($redisorder['drift'])&&!empty($redisorder['drift'])&&$redisorder['protype']==1){
                $money = $money + $orders['drift']*$money/100;
                $change = $orders['drift']*$money/100;
                $redisorder['difference'] = $redisorder['difference'] + $redisorder['drift']*$redisorder['difference']/100;
                $price['sellprice'] = $orders['buyprice'] + $redisorder['difference']*$redisorder['rands'];
            }
            //写入减仓
            $data=[
                'order_no'=>$order['order_no'],
                'orderid'=>$order['id'],
                'type'=>3,
                'aid'=>$order['aid'],
                'pid'=>$order['pid'],
                'proid'=>$order['proid'],
                'protype'=>$orders['protype'],
                'buyprice'=>$orders['buyprice'],
                'sellprice'=>$price['price'],
                'point'=>json_encode($orders['point'],JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE),
                'money'=>round($money,2),
                'change'=>round($change,2),
                'bondsum'=>round($moneysum,2),
                'closesum'=>round(($pro['ratio']*$moneysum/100),2),
                'warnsum'=>round(($pro['warn']*$moneysum/100),2),
                'puffs'=>$params['puffs'],
                'wlpoint'=>$redisorder['difference'],
                'win'=>$order['win'],
                'status'=>2,
                'amount'=>$amount,
                'backamount'=>$backamount,
                'updatetime'=>date('Y-m-d H:i:s',time()),
                'createtime'=>date('Y-m-d H:i:s',time())
            ];
            $this->model->addorderlog($data);
            unset($data);
            //更新剩余口数
            $bondsum = ($orders['bondsum']-$moneysum);
            $data=[
                // 'orderid'=>$params['orderid'],
                'bondsum'=>round($bondsum, 2),
                'sellprice'=>$price['price'],
                'closesum'=>round(($pro['ratio']*$bondsum/100),2),
                'warnsum'=>round(($pro['warn']*$bondsum/100),2),
                'wlpoint'=>$redisorder['difference'],
                'puffs'=>($orders['puffs']-$params['puffs']),
                'amount'=>$amount,
                'backamount'=>$backamount,
                'updatetime'=>date('Y-m-d H:i:s',time())
            ];
            if($orders['puffs']-$params['puffs']==0){
                $data['status']=2;
                $data['sellprice']=0;
                $data['wlpoint']=0;
                // $data['win']=$money>0?1:2;
                // $data['money']=round($money,2);
                $this->model->execRedis('hdel',[config('tradecontrol.order'), $orders['id']]);
                $this->model->execRedis('hdel',[config('tradecontrol.order').$order['aid'], $orders['id']]);
            }else{
                $redisorder['puffs']=$orders['puffs']-$params['puffs'];
                $redisorder['bondsum']=round($bondsum, 2);
                $redisorder['closesum']=round(($pro['ratio']*$bondsum/100),2);
                $redisorder['warnsum']=round(($pro['warn']*$bondsum/100),2);
                $this->model->execRedis('hset',[config('tradecontrol.order'), $orders['id'],json_encode($redisorder)]);
            }
            $this->model->updateorderlog(' id = '.$params['id'], $data);
            //更新账户余额
            $accmoney = $this->model->execRedis('hget',[$control['amount'], $order['aid']]);
            if(!empty($accmoney)){$accmoney = json_decode($accmoney, true);}else{$accmoney=[];}
            switch ($order['type']) {
                case 1:
                    (new CommonModel())->updateAccount('aid='.$order['aid'],['amount'=>$backamount]);
                    $accmoney[$order['type']]=$backamount;
                    $this->model->execRedis('hset',[$control['amount'], $order['aid'],json_encode($accmoney)]);
                    break;
                case 2:
                    (new CommonModel())->updateAccount('aid='.$order['aid'],['giftamount'=>$backamount]);
                    $accmoney[$order['type']]=$backamount;
                    $this->model->execRedis('hset',[$control['amount'], $order['aid'],json_encode($accmoney)]);
                    break;
                default:
                    return $this->echojson(Lang::get('Parerror'));
                    break;
            }
            $data = [
                'money'=>$order['money']+$money,
                'updatetime'=>date('Y-m-d H:i:s',time())
            ];
            //判断是否还有订单记录计算
            $record=$this->model->getorderloginfo('status<2 and orderid='.$order['id'],'id');
            if(!isset($record['id']) || empty($record['id'])){
               $data['status']=2;
            }else{
               $data['status']=1; 
            }
            $this->model->updateorder('id='.$order['id'],$data);
            (new CommonModel())->commit();
            //判斷是否還有其他訂單記錄
            $count=$this->model->getorderloginfo('status<2 and aid='.$this->login['aid'],'count(id) as id');
            if($count['id']<1){
                $this->model->execRedis('hdel',[$control['amount'], $user['aid']]);
            }
            $this->success['data']=['status'=>$data['status']];
            return $this->echojson($this->success);
        } catch (Exception $e) {
            (new CommonModel())->rollback();
            return $this->echojson(Lang::get('Parerror'));
        }
    }

    /**
     * 改變訂單停損停利
     * @param array $changeOrder 
     * @param array $where 
     */ 
    public function changeOrder(){
        $params = post();
        //判斷參數是否存在
        if(empty($params['id']) || empty($params['protype'])) return $this->echoJson(Lang::get('Ordererror'));
        if($params['protype']==2 && (empty($params['winpoint']) || empty($params['losspoint']))){ return $this->echoJson(Lang::get('Ordererror')); }
        //判斷用户
        if(empty($this->login['aid'])) return $this->echoJson(Lang::get('Getusererror'));
        $user=(new CommonModel())->getAccount('aid='.$this->login['aid'],['amount','giftamount']);
        //获取订单記錄
        $orders = $this->model->getorderloginfo('id='.$params['id'],'id,orderid,protype,point');
        $key = config('tradecontrol.order');
        // 獲取產品
        $redisorder = $this->model->execRedis('hget',[$key, $orders['id']]);
        if(!empty($redisorder)){
            $redisorder = json_decode($redisorder,true);
        }else{
            return $this->echoJson(Lang::get('Nodata'));
        }
        //开启事务
        (new CommonModel())->startTrans();
        //初始化盈虧點數及計算盈虧點數
        $difference=0;
        $difference = $redisorder['difference'];
        switch ($params['protype']) {
            case 1:
                $orders['point']['winpoint']=0;
                $orders['point']['losspoint']=0;
                break;
            case 2:
                $orders['point']['winpoint']=$difference>=0?(round(abs($difference),4)+$params['winpoint']):$params['winpoint'];
                $orders['point']['losspoint']=$difference<0?(round(abs($difference),4)+$params['losspoint']):$params['losspoint'];
                break;          
            default:
                return $this->echoJson(Lang::get('Nodata'));
                break;
        }
        try {
            $data=[
                'protype'=>$params['protype'],
                'point'=>json_encode($orders['point'],JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE),
                'updatetime'=>date('Y-m-d H:i:s',time())
            ];
            $this->model->updateorderlog(' id = '.$params['id'], $data);
            //更新redis
            $redisorder['protype']=$params['protype'];
            $redisorder['point']=$orders['point'];
            $this->model->execRedis('hset',[config('tradecontrol.order'), $orders['id'],json_encode($redisorder)]);
            $data = [
                'updatetime'=>date('Y-m-d H:i:s',time())
            ];
            $this->model->updateorder('id='.$orders['orderid'],$data);
            (new CommonModel())->commit();
            return $this->echojson($this->success);
        } catch (Exception $e) {
            (new CommonModel())->rollback();
            return $this->echojson(Lang::get('Parerror'));
        }
    }
    
}